// pages/yes/index.js
const http = require('../../api/index')
const request = require('../../utils/request')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    typename: 'camp_camp_camptype_status',
    showtype: false,
    camptype: null,
    camptypelist: [],
    campLocation: '',
    latitude: '',
    longitude: '',
    address: null,
    time: '', //营业时间
    contacts: '', //联系人
    phone: '', //联系电话
    introduce: '', //营地内容
    timeType: '1',
    campId: '',
    facilityIds: [],
    showadress: false,
    //弹出层
    price: '250',
    checked: true,
    //步骤条
    active: 0,
    //初始为第一页
    viewshow: 1,
    //步骤条
    steps: [{
        text: '营地信息'
      },
      {
        text: '服务设施'
      }
    ],
    facility: [],
    facilitiesList: [],
    selectFacilitiesList: [],
    imgUrl: request.baseURL,
    introduce: "",
    campImgs: [],
    fileList: [],
    baseURL: request.baseURL,
    camptypeSelect: ['综合营地', '微型营地', '帐篷营地', '教育营地', '运动营地', '无人值守驻车点', ]
  },
  getUploadList(l) {
    console.log(l.detail)
    this.setData({
      campImgs: l.detail,
      tourisCampImgs: l.detail
    })
    console.log('')
  },
  addCamp() {
    console.log("添加的信息：", this.data)
  },
  //上一步
  btnPre() {
    var newActive = --this.data.active;
    var newViewshow = --this.data.viewshow;
    if (newActive >= 0) {
      this.setData({
        active: newActive,
        viewshow: newViewshow
      })
    }
  },
  delImgs(u) {
    this.data.campImgs.splice(u.currentTarget.dataset.index, 1)
    this.setData({
      campImgs: this.data.campImgs
    })
  },
  //下一步
  btnNext() {
    var newActive = ++this.data.active;
    console.log('newActive', newActive);
    var newViewshow = ++this.data.viewshow;
    if (newActive >= 3) {
      console.log('这就是最后一页！！');
      wx.showToast({
          icon: 'none',
          title: '这就是最后一页！！',
          duration: 1500
        })
        --this.data.active;
      --this.data.viewshow;
    } else {
      this.setData({
        active: newActive,
        viewshow: newViewshow
      })
    }
  },
  //弹出层的显示与关闭
  showPopup() {
    this.setData({
      showtype: true
    });
  },
  onClose() {
    this.setData({
      showtype: false,
      camptype: null
    });
  },
  onChange(e) {
    this.setData({
      timeType: e.detail
    })
    if (e.detail == 1) {
      this.setData({
        timeDetailOpen: false,
        time: "全年"
      })
    } else {
      this.setData({
        timeDetailOpen: true
      })
    }
  },
  onChange(event) {
    const {
      value
    } = event.detail;
    this.setData({
      camptype: value
    });
  },
  onChangeType(event) {
    const {
      value
    } = event.detail;
    this.setData({
      camptype: value
    });
  },
  onConfirm() {
    this.setData({
      showtype: false,
    });
  },
  //单选按钮点击
  onClick(event) {
    const {
      name
    } = event.currentTarget.dataset;
    this.setData({
      camptype: name,
    });
  },
  // 营地位置
  selectSite() {
    // 检查用户权限状态
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userLocation']) {
          // 用户尚未授权或已拒绝授权
          // 主动请求授权
          this.requestLocationAuthorization();
        } else {
          // 已经授权，直接获取位置信息
          this.getUserLocation();
        }
      }
    })
  },
  //获取位置信息
  getUserLocation() {
    wx.getLocation({
      // type: 'wgs84',
      type: 'gcj02',
      success: (res) => {
        console.log(res, "返回的数据")
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        });
        wx.chooseLocation({
          longitude: this.data.longitude,
          latitude: this.data.latitude,
          success: (res) => {
            console.log(res, '########');
            this.setData({
              latitude: res.latitude,
              longitude: res.longitude,
              campLocation: res.address
            });
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: (err) => {
        console.error('获取位置失败:', err);
      },
      complete: () => {
        console.log('位置获取操作已完成');
      }
    });
  },
  // 请求授权
  requestLocationAuthorization() {
    // 请求用户授权精确位置
    wx.authorize({
      scope: 'scope.userLocation',
      success: () => {
        this.getUserLocation();
      },
      fail: (err) => {
        // 拒绝授权，提示用户收到开启
        this.showSettingPrompt()
      }
    })
  },
  showSettingPrompt() {
    wx.showModal({
      title: '需要位置权限',
      content: '请在设置中开启位置权限以正常使用本功能。',
      showCancel: false,
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) {
          wx.openSetting({
            success: (settingRes) => {
              if (settingRes.authSetting['scope.userLocation']) {
                // 用户在设置中开启了位置权限
                this.getUserLocation();
              } else {
                // 用户仍然拒绝位置权限
                console.log('用户仍未开启位置权限');
              }
            },
          });
        }
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.getDict(this.data.typename);s
    this.getUserType();
    console.log('zuobiao', options);
    this.setData({
      campLocation: options.addr,
      latitude: options.latitude,
      longitude: options.longitude,
    })

    console.log('userType', this.data.userType);
    this.getfacility();
  },
  // 获取设施列表
  getfacility() {
    http.facilityTypeList().then((res) => {

      if (res.code === 200) {
        this.setData({
          facilitiesList: res.rows,
        })
        console.log('facilitiesList', this.data.facilitiesList);
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //选中服务设施
  selectIcon(e) {
    console.log(list)
    let a, b, select, list, id, data
    list = this.data.facilitiesList
    id = e.currentTarget.dataset.id
    data = this.data.selectFacilitiesList
    for (let i = 0; i < list.length; i++) {
      for (let j = 0; j < list[i].facilities.length; j++) {
        if (id == list[i].facilities[j].facilityId) {
          a = i
          b = j
        }
      }
    }
    select = list[a].facilities[b].state

    //如果没有选中
    if (select == 1) {
      list[a].facilities[b].state = 2
      data.push(id)
      this.setData({
        facilitiesList: list,
        selectFacilitiesList: data,
      })
    } else {
      list[a].facilities[b].state = 1
      let index = data.indexOf(id)
      data.splice(index, 1)
      this.setData({
        facilitiesList: list,
        selectFacilitiesList: data,
      })
    }
    console.log(this.data.selectFacilitiesList);
  },
  getUserType() {
    let that = this;
    console.log('that', that);
    wx.getStorage({
      key: 'userTypeId',
      success(res) {
        that.setData({
          userType: res.data.userType
        })

      },
      fail(err) {
        console.error('缓存读取失败：', err);
      },
    });

  },
  getDict(e) {
    console.log("getDict");
    http.dictList(e).then(res => {
      console.log('res', res)
      if (res.code === 200) {
        this.setData({
          camptypelist: res.data
        })
        // this.data.camptypeSelect = 
        this.setData({
          camptypeSelect: this.data.camptypelist.map(item => item.dictLabel)
        })
        console.log('camptypeSelect', this.data.camptypeSelect)
      }
    })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getDict(this.data.typename);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  async readStorage() {
    let that = this;

    wx.getStorage({
      key: 'userTypeId', // 缓存的键
      success(res) {
        console.log('读取成功，值为：', res.data); // 缓存中的值
        that.setData({
          userType: res.data.userType
        })
      },
      fail(err) {
        console.error('读取失败：', err);
      }
    });

  },
  // 运营者提交数据
  async businessSub() {

    await this.readStorage()
    await this.subCamp()
    await this.subService()

  },
  // 提交营地信息
  async subCamp() {
    console.log('地址', this.data.campImgs)
    let userInfo = wx.getStorageSync("userInfo")
    let campType = this.campType(this.data.type)
    let res = await http.addCamp({
      userId: userInfo.userId,
      userType: this.data.userType,
      campType,
      campName: this.data.name,
      longitude: this.data.longitude, //经度
      latitude: this.data.latitude,
      location: this.data.campLocation,
      address: this.data.address,
      timeType: this.data.timeType,
      specificTime: this.data.time,
      linkman: this.data.contacts,
      phone: this.data.phone,
      imageUrl: this.data.campImgs.join(","),
      introduce: this.data.introduce,

    })
    this.setData({
      campId: res.msg
    })
  },
  // 返回营地类型id
  campType(value) {
    return this.data.camptypeSelect.indexOf(value) + 1
  },
  // 上传服务设施
  async subService() {
    let res = await http.addFacility({
      campId: this.data.campId,
      facilityIds: this.data.selectFacilitiesList
    })
    console.log('13')
    console.log('code', res.code)
    console.log('res', res);
    if (res.code == 200) {
      console.log('跳转');
      wx.switchTab({
        url: '/pages/index/index',
      })
      console.log('跳转2');
    }
  },
  //营业时间
  selectTime() {
    this.setData({
      open: false,
      timeOpen: true,
      time: "全年"
    })
  },
  // 关闭时间
  closeTime() {
    this.setData({
      timeOpen: false
    })
  },
  // 确定时间
  sureTime() {
    this.setData({
      timeOpen: false
    })
    console.log(this.data.time)
  },


})